package main

import (
	"context"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	trippd "goStudy/proto/gen/go"
	trip "goStudy/tripservice"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net"
	"net/http"
)

func main() {
	//这里是tcp协议监听，内部走的是二进制的数据，也就是微服务的内部
	listen, err := net.Listen("tcp", ":8083")
	if err != nil {
		panic(err)
	}
	go startGRPCGateway()

	server := grpc.NewServer()
	trippd.RegisterTripServiceServer(server, &trip.Service{})
	log.Fatal(server.Serve(listen))
}
func startGRPCGateway() {
	c := context.Background()
	c, cancelFunc := context.WithCancel(c)
	mux := runtime.NewServeMux()
	defer cancelFunc()
	//他做的是就是将gateway网关的数据转发给grpc内部相对应的微服务，实际上是建立相关连关系
	err := trippd.RegisterTripServiceHandlerFromEndpoint(
		c,
		//这是一个分发器
		mux,
		"localhost:8083",
		[]grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())},
	)
	if err != nil {
		log.Fatal("测试失败")
	}
	err = http.ListenAndServe(":8087", mux)
	if err != nil {
		log.Fatal("gateway网关链接内部服务器错误")
	}
}
